package com.zx.config;/**
 * Author:JasonZ
 * Data:2023/4/18
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.zx.constant.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @program: ecommerce-parent
 *
 * @description:
 *
 * @author: JasonZ
 *
 * @create: 2023-04-18 10:07
 **/
@Component
@Slf4j
public class DynamicRoutesServiceByNacos {
    /*nacos提供的提供相关配置动态路由的参数 封装在包里*/
    private ConfigService configService;

    @Resource
    private DynamicRoutesService routesService;

    /*在这个类被构造完之后自动执行*/
    @PostConstruct
    public void init() throws NacosException {
        log.info("gateway route init.....");
        // 如果configService代表的是nacos的配置服务
        // 想要构建configService 必须知道nacos的服务地址
        //构建properties
        Properties prop = new Properties();
        prop.setProperty("serverAddr", GatewayConstant.NACOS_SERVER_ADDR);
        prop.setProperty("namespace",GatewayConstant.NACOS_NAMESPACE);
        configService= NacosFactory.createConfigService(prop);
        //获取配置信息
        String config = configService.getConfig(GatewayConstant.NACOS_DATA_ID,
                GatewayConstant.NACOS_CONFIG_GROUP,
                GatewayConstant.DEFAULT_TIMEOUT);
        log.info("load config: [{}]",config);
        // 转换成RouteDefnition对象
        List<RouteDefinition> routeDefinitions = JSON.parseArray(config, RouteDefinition.class);
        //把配置信息配置到nacos当中
        routeDefinitions.forEach(r->routesService.addRouteDefinition(r));
        //添加一个监听 监视配置文件的变化
        configService.addListener(GatewayConstant.NACOS_DATA_ID, GatewayConstant.NACOS_CONFIG_GROUP, new Listener() {
            @Override
            public Executor getExecutor() {
                /*返回一个线程池 如果返回为空 就是使用默认的线程池*/
                return null;
            }
            @Override
            public void receiveConfigInfo(String s) {
                log.info("update config: [{}]",s);
                List<RouteDefinition> routes = JSON.parseArray(s, RouteDefinition.class);
                routesService.updateList(routes);
            }
        });
    }
}
